package com.school.base.service;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.school.base.dao.INewsDao;
import com.school.base.model.News;
import com.school.common.tags.PageBean;

public class NewsService {
	private static Logger logger = Logger.getLogger(NewsService.class);
	private INewsDao newsDao;

	public INewsDao getNewsDao() {
		return newsDao;
	}

	public void setNewsDao(INewsDao newsDao) {
		this.newsDao = newsDao;
	}

	public News getNewsById(int id) {
		return newsDao.getNewsById(id);
	}

	public List<News> getNewsList(News news, PageBean pageBean) {
		if (pageBean == null) {
			pageBean = new PageBean();
		}
		pageBean.setTotalRecordCount(newsDao.getTotalCount(news));
		return newsDao.getNewsList(news, pageBean.getOffset(), pageBean.getPageSize());
	}

	private void validateOption(News news) throws Exception {
		if (news==null) {
			logger.error("the news object is empty.");
			throw new Exception("news 对象为空");
		}
		if (news.getTitle() == null || news.getTitle().isEmpty()) {
			logger.error("the news's title is empty.");
			throw new Exception("新闻标题不能为空");
		}
	}

	public void updateNews(News news) throws Exception {
		this.validateOption(news);
		newsDao.updateNews(news);
	}

	public void deleteNews(int id) {
		newsDao.deleteNews(id);
	}

	public void insertNews(News news, int creatorId) throws Exception {
		this.validateOption(news);
		news.setCreateTime(new Date());
		news.setClicks(0);
		news.setCreatorId(creatorId);
		newsDao.insertNews(news);
	}

	public void updateNewsSticky(int newsId, int to) {
		newsDao.updateNewsSticky(newsId, to);
	}
}
